---
category: String
created: '2021-03-21'
title: Generate a hash of a string
updated: '2021-10-13'
---

**JavaScript version**

```js hash.js
const hash = (str) => str.split('').reduce((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0);

// Or
const hash = (str) => str.split('').reduce((prev, curr) => ((prev << 5) - prev + curr.charCodeAt(0)) | 0, 0);
```

**TypeScript version**

```ts hash.ts
const hash = (str: string): number =>
    str.split('').reduce((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0);

// Or
const hash = (str: string): number =>
    str.split('').reduce((prev, curr) => ((prev << 5) - prev + curr.charCodeAt(0)) | 0, 0);
```

**Examples**

```js examples.js
hash('hello'); // 99162322
```
